<?php

defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
|  订单模型
|@author khj
|--------------------------------------------------------------------------
*/
class Order extends MY_Controller {
    /**
     * 商家模型
     * @var MerchantUserModel
     */
    public $mMerchant;

    /**
     * 分类模型
     * @var ConsumerCategoryModel
     */
    public $mCategory;

    /**
     * 评论模型
     * @var MerchantCommentModel
     */
    public $mComment;

    /**
     * 产品模型
     * @var ConsumerProductModel
     */
    public $mProduct;

    /**
     * 订单模型
     * @var ConsumerOrderModel
     */
    public $mOrder;

    /**
     * 支付模型
     * @var ConsumerPayModel
     */
    public $mPay;

    public function __construct(){
        parent::__construct();

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

    }


    /**
     * 获取我的订单
     */
    public function orderList(){

        $type = (int)get('type');
        $status = get('status')?get('status'):0;
        $page = get('page')?get('page'):1;
        $type = $type == 0 ? 1 : $type;
        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

        //验证
        if ( $status && ! array_key_exists($status, $this->mOrder->STATUS)){
            show_404();
        }
        if(!in_array($type, array(1,2))){
            show_404();
        }

        /**
         * 获取订单列表
         * @var Ambiguous $tA
         */
        $tA = $this->mOrder->appGetList($this->userId, $type, $status,$page, $this->port);
        $dTime = array();
        if($tA){
            /**
             * 获取订单商家信息
             */
            $tMerchant = array();
            $tOrder = array();
            $tMerchantIds = array();
            $tOrderIds = array();
            foreach ($tA as $k=>$v){
                if (! in_array($v['merchant_id'], $tMerchantIds)){
                    $tMerchantIds[] = $v['merchant_id'];
                }
                if (! in_array($v['id'], $tOrderIds)){
                    $tOrderIds[] = $v['id'];
                }
            }

            if( ! $tMerchantIds || ! $tOrderIds){
                show_404();
            }

            /**
             * 获取订单信息
             * @var array $tOrderProduct
             */
            $tOrderProduct = $this->mOrder->getOrderProductInfoByIds(array(),$tOrderIds);
            if( ! $tOrderProduct){
                show_404();
            }

            /**
             * 获取商家信息
             */
            $tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
            if( ! $tMerchant){
                show_404();
            }

            /**
             * 订单数据
             */

            foreach ($tA as $k=>$v){
                $dTime[] = ['order_id' => $v['id'], 'addtime' => $v['addtime']];
                $tA[$k]['shop_name'] = isset($tMerchant[$v['merchant_id']]['shop_name'])?$tMerchant[$v['merchant_id']]['shop_name']:'暂无';
                $tA[$k]['portrait'] = isset($tMerchant[$v['merchant_id']])?$tMerchant[$v['merchant_id']]['portrait']['xs']:'暂无';
                $tA[$k]['title'] = isset($tOrderProduct[$v['id']]) ? $tOrderProduct[$v['id']][0]['name']:'暂无';

                //如果字符串大于10 则省略
                if (strlen($tA[$k]['title'])>10){
                    $tA[$k]['title'] = mb_substr($tA[$k]['title'],0,10).'..等'.count($tOrderProduct[$v['id']]).'件商品';
                }else{
                    $tA[$k]['title'] = $tA[$k]['title'].'等'.(isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0").'件商品';
                }

                $tA[$k]['count'] = isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0";
            }
        }

        $tData = array(
            'title' => '我的订单',
            'active' => 'order',
            'type' => $type,
            'status' => $status,
            'addtimes' => json_encode($dTime),
            'number' => $this->mOrder->getOperateOrderNumber(0, $this->userId),
            'list' => $tA
        );

        $this->view('order/orderList', $tData,'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * ajax 获取列表数据
     */
    public function getOrderList(){

        $type = post('type');
        $status = post('status')?post('status'):0;
        $page = post('page');
        $page = $page ? $page + 1 : 1;
        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

        //验证
        if ( $status && ! array_key_exists($status, $this->mOrder->STATUS)){
            $this->ajaxReturn(0, '状态错误');
        }
        if(!in_array($type, array(1,2))){
            $this->ajaxReturn(0, '类型错误');
        }

        /**
         * 获取订单列表
         * @var Ambiguous $tA
         */
        $tA = $this->mOrder->appGetList($this->userId, $type, $status,$page, $this->port);
        if($tA){
            $tMerchantIds = array();
            $tOrderIds = array();
            foreach ($tA as $k=>$v){
                if (! in_array($v['merchant_id'], $tMerchantIds)){
                    $tMerchantIds[] = $v['merchant_id'];
                }
                if (! in_array($v['id'], $tOrderIds)){
                    $tOrderIds[] = $v['id'];
                }
            }

            if( ! $tMerchantIds || ! $tOrderIds){
                show_404();
            }

            /**
             * 获取订单信息
             * @var array $tOrderProduct
             */
            $tOrderProduct = $this->mOrder->getOrderProductInfoByIds(array(),$tOrderIds);
            if( ! $tOrderProduct){
                show_404();
            }

            /**
             * 获取商家信息
             */
            $tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
            if( ! $tMerchant){
                show_404();
            }

            /**
             * 订单数据
             */
            foreach ($tA as $k=>$v){
                $tA[$k]['shop_name'] = isset($tMerchant[$v['merchant_id']]['shop_name'])?$tMerchant[$v['merchant_id']]['shop_name']:'暂无';
                $tA[$k]['portrait'] = isset($tMerchant[$v['merchant_id']])?$tMerchant[$v['merchant_id']]['portrait']['xs']:'暂无';
                $tA[$k]['title'] = isset($tOrderProduct[$v['id']]) ? $tOrderProduct[$v['id']][0]['name']:'暂无';

                //如果字符串大于10 则省略
                if (strlen($tA[$k]['title'])>10){
                    $tA[$k]['title'] = mb_substr($tA[$k]['title'],0,10).'..等'.count($tOrderProduct[$v['id']]).'件商品';
                }else{
                    $tA[$k]['title'] = $tA[$k]['title'].'等'.(isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0").'件商品';
                }

                $tA[$k]['count'] = isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0";
            }
        }
        $this->ajaxReturn(1, '', $tA);
    }

    /**
     * 订单立即收货
     */
    public function orderReceive(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $this->formDataValidation($vConf);

        $orderId = post('order_id');

        $tA = $this->mOrder->getInfo($orderId,$this->userId, 0, true);
        if ( ! $tA){
            $this->appReturn(0,'订单不存在');
        }

        //是否待收货
        if ($tA['status'] != 3){
            $this->appReturn(0,'该订单无法确认收货');
        }

        $this->db->trans_begin();

        $result = $this->mOrder->_confirmReceipt($orderId,'立即收货',$tA['merchant_id'], $this->port, $this->userId);

        if ($result['status'] == 0){
            $this->db->trans_rollback();
            $this->appReturn(0, $result['message']);
        }
        //用户推送消息
        $msgData = array(
            'title' => '订单已收货',
            'content' => '您的订单已签收',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMsg', 'consumer');
        if(!($this->mMsg->save($msgData, 0, $orderId))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgInfo = $this->mMsg->getInfo(0, 0, 0, $orderId);
        //删除消息查看记录
        $this->mMsg->deleteView($this->userId, $msgInfo['id']);
        jpush($msgData['title'], $msgData['content'], 1, array($tA['jpush_code']), 3, $orderId, $tA['expense_type']);

        //商家推送消息
        $merMsg = array(
            'title' => '订单已收货',
            'content' => '订单已被用户签收',
            'addtime' => time(),
        );
        $this->loadModel('merchantMessageModel', 'mMerMsg', 'merchant');
        if(!($this->mMerMsg->save($merMsg, 0, $orderId))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgIn = $this->mMerMsg->getInfo(0, $tA['merchant_id'], $orderId);
        //删除消息查看记录
        $this->mMerMsg->deleteView($tA['merchant_id'], $msgIn['id']);
        MerchantJpush($merMsg['title'], $merMsg['content'], 1, array($tA['merchant_jpush_code']), 3, $orderId);

        $this->db->trans_commit();
        $this->appReturn(1,'确认收货成功');
    }

    /**
     * 立即支付
     */
    public function orderPay(){
        //表单验证
        $vConf = array(
            array('code', '订单号', 'required'),
        );
        $this->formDataValidation($vConf);

        $code = post('code');

        //如果解析成功
        $arrayCode = json_decode($code,true);

        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
        $this->loadModel('ConsumerPayModel', 'mPay', 'consumer');

        $amount = 0;
        $tempCode = array();
        if (is_array($arrayCode)){
            $tOrders = $this->mOrder->getInfoByCodes($arrayCode);
            if ( ! $tOrders){
                $this->appReturn(0,'订单不存在');
            }

            foreach ($tOrders as $k=>$v){
                if ($v['status'] != 1){
                    //待支付
                    $this->appReturn(0,'订单已经被取消');
                }
                $tempCode[] = $v['code'];
                $amount += $v['reality_amount'];
            }
        }else{

            $tOrder = $this->mOrder->getInfoByCode($code, 0,$this->userId);
            if ( ! $tOrder){
                $this->appReturn(0,'订单不存在');
            }
            if ($tOrder['status'] != 1){
                //待支付
                $this->appReturn(0,'订单已经被取消');
            }

            $tempCode[] = $tOrder['code'];
            $amount = $tOrder['reality_amount'];
        }

        /**
         * 创建预支付订单
         */
        $this->db->trans_begin();//事务

        $payCode = getOrderCode();
        $data = array(
            'consumer_id'=>$this->userId,
            'code'=>$payCode,
            'amount'=>$amount,
            'type'=>2,//充值
            'pay_type'=>0, //没有支付方式
            'status'=>1,//未支付
            'param'=>json_encode($tempCode),
            'addtime'=>time(),
        );

        if ( ! $this->mPay->savePayOrder($data)){
            $this->db->trans_rollback();
            $this->appReturn(0,'调起支付失败[ERROR:01]');//预支付订单失败
        }

        /**
         * 更新订单预支付订单号
         */
        if ( ! $this->mOrder->saveBatch(array('pay_code'=>$payCode),0,$tempCode)){
            $this->db->trans_rollback();
            $this->appReturn(0,'调起支付失败[ERROR:02]');
        }

        /**
         * 获取支付参数
         */
        $tA['code'] = $payCode;
        $tA['amount'] = $amount;
        //获取支付宝
        $tA['alipay'] = $this->mPay->_getAliPay($payCode,$amount);
        //获取微信支付
        $tA['wxpay'] = $this->mPay->_getWxPay($payCode,$amount);

        $this->db->trans_commit();
        $this->appReturn(1,'',$tA);
    }

    /**
     * 取消订单
     */
    public function orderCancel(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $orderId = get('order_id');
        $this->formDataValidation($vConf,array('order_id' => $orderId));

        $tA = $this->mOrder->getInfo($orderId,$this->userId);
        if ( ! $tA){
            $this->ajaxReturn(0,'订单不存在');
        }
        $status = 7;
        //是否待支付
        if ($tA['status'] != 1 && $tA['status'] != 2){
            $this->ajaxReturn(0,'该订单无法取消');
        }

        $this->db->trans_begin();
        if($tA['status'] == 2){
            //商家未接单前 取消已支付订单 原路退款
            $result = $this->mOrder->_OrderRefund($orderId, $this->userId,$tA['reality_amount'],$tA['pay_type'],
                $tA['wx_type'], $tA['pay_code'], $tA['code']);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, $result['message']);
            }
            $status = 8;
        }
        //商品增加库存
        $this->loadModel('AdmSettingModel', 'mSet','admin');
        $reduce_stock = $this->mSet->get('reduce_stock');

        if ($reduce_stock == 1){
            //下单时减少
            $result = $this->mOrder->reduceStocks($orderId, true);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, $result['message']);
            }
        }
        if ( ! $this->mOrder->save(array('status'=> $status),0,$orderId)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0,'订单取消失败');
        }

        $rS = $this->mOrder->saveOrderLog($orderId, '交易关闭', '消费者取消了订单', $this->port, $this->userId);
        if (!$rS){
            $this->ajaxReturn(0,'取消失败[ERROR:02]');
        }

        //如果使用包邮卡 退回
        if($tA['postal_card'] > 0){
            $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');

            $this->db->where('order_id', $orderId);
            $query = $this->mPostalCard->update($this->mPostalCard->tbPostalCardLog,
                array(
                    'status' => 1,
                    'order_id' => 0,
                    'usedtime' => ''
                )
            );
            if ( !$query){
                $this->db->trans_rollback();
                $this->appReturn(0,'包邮卡退还失败');
            }
        }

        $this->db->trans_commit();
        $this->ajaxReturn(1,'取消成功', '', getUrl('order/orderDetail?order_id='.$orderId));
    }

    /**
     * 删除订单
     */
    public function orderRemove(){
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $orderId = get('order_id');
        $this->formDataValidation($vConf, array('order_id' => $orderId));

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');

        $tA = $this->mOrder->getInfo($orderId,$this->userId);
        if ( ! $tA){
            $this->appReturn(0,'订单不存在');
        }

        //是否待支付 7-取消  5-完成 才能删除
        if ( ! in_array($tA['status'], [1,5,6,7])){
            $this->appReturn(0,'该订单无法删除');
        }

        $this->db->trans_begin();
        if ($tA['status'] == 7){
            //真删除订单
            $this->db->where('id',$orderId);
            if ( ! $this->db->delete($this->mOrder->tbOrder)){
                $this->db->trans_rollback();
                $this->appReturn(0,'删除订单失败[ERROR:01]');
            }

            //删除订单产品
            $this->db->where('order_id',$orderId);
            if ( ! $this->db->delete($this->mOrder->tbOrderProduct)){
                $this->db->trans_rollback();
                $this->appReturn(0,'删除订单失败[ERROR:02]');
            }
            // 删除产品操作记录
            $rS = $this->mOrder->deleteOrderLog($orderId);
            if (!$rS){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '删除订单失败[ERROR:03]');
            }
            //删除消息记录
            $this->mMessage->deleteMsg($orderId, $this->userId);

        }elseif (in_array($tA['status'], [5,6])){
            //订单完成的 假删除

            if ( ! $this->mOrder->save(array('is_consumer_delete'=>2),0,$orderId)){
                $this->db->trans_rollback();
                $this->appReturn(0,'订单删除失败');
            }
            $rS = $this->mOrder->saveOrderLog($orderId, '删除订单', '消费者删除了完成的订单', $this->port, $this->userId);
            if (!$rS){
                $this->appReturn(0,'取消失败[ERROR:02]');
            }

        }

        $this->db->trans_commit();
        $this->ajaxReturn(1,'删除成功', '', getUrl('order/orderList?type=1&status=0'));
    }

    /**
     * 催一下
     */
    public function push(){
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $orderId = get('order_id');
        $this->formDataValidation($vConf, array('order_id' => $orderId));


        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getInfo($orderId,$this->userId,0);
        if ( ! $tA){
            $this->appReturn(0,'订单不存在');
        }
        if($tA['last_push_time'] && time() - $tA['last_push_time'] < 5*60){
            $this->appReturn(0,'催单频繁，请稍后再试');
        }
        //更新催单时间
        if(!($this->mOrder->save(array('last_push_time' => time()), 0, $orderId))){
            $this->appReturn(0,'催单失败');
        };
        MerchantJpush('催单消息', '订单：'.$tA['code'].'已经等不及了，请尽快配送', 1, array($tA['merchant_jpush_code']), 3, $orderId);

        $this->appReturn(1, '催单成功');
    }

    /**
     * 获取物流跟踪信息
     */
    public function getOrderExpress(){
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        $orderId = get('order_id');

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getInfo($orderId, $this->userId);
        if ( ! $tA){
            $this->appReturn(0, '订单不存在');
        }
        if(!in_array($tA['status'], array(3,4,5)) || $tA['shipping_type'] != 2){
            $this->appReturn(0, '暂无配送信息');
        }
        //配送信息
        $traces = array();
        //获取配送信息
        $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
        $dlnOrder = $this->mDlnOrder->getDeliverymanInfoByOrderIds(array($orderId));
        $dlnOrder = $dlnOrder[$orderId];
        if($dlnOrder['status'] == 1){
            $traces[] = array('status' => '配送'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
        }elseif ($dlnOrder['status'] == 2){
            $traces[] = array('status' => '配送'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送已接单','time' => $dlnOrder['addtime']);
        }
        elseif ($dlnOrder['status'] == 3){
            $traces[] = array('status' => '配送'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送已接单','time' => $dlnOrder['addtime']);
        }elseif ($dlnOrder['status'] == 4){
            $traces[] = array('status' => '配送已完成','time' => $dlnOrder['complete_time']);
            $traces[] = array('status' => '配送已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送已接单','time' => $dlnOrder['addtime']);
        }
        $traces[] = array('status' => '商家已接单','time' => date('m-d H:i',$tA['merchant_take_time']));

        $ak = $this->mSett->get('map_key','deliveryman');

        $html = $this->view('order/shopper_details',[
                'ak'=>$ak,
                'active' => 'order',
                'delivery_latitude'=>$dlnOrder['latitude'],
                'delivery_longitude'=>$dlnOrder['longitude'],
                'shop_longitude'=>$tA['shop_longitude'],
                'shop_latitude'=>$tA['shop_latitude'],
                'send_to_latitude'=>$tA['latitude'],
                'send_to_longitude'=>$tA['longitude'],
                'Traces'=>$traces,
            ]);

    }

    /**
     * 获取订单详情
     */
    public function orderDetail(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $orderId = (int)get('order_id');

        $tA = $this->mOrder->appGetInfo($orderId,$this->userId, '', '', $this->port);

        if ( ! $tA){
            show_404();
        }
        if ($tA['shipping_type'] == 2){//平台配送
            $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');
            $deliveryman = $this->mDln->getDeliverymanInfoByOrderIds(array($orderId));
            $tInfo = isset($deliveryman[$orderId])?$deliveryman[$orderId]:array();
            if($tInfo){
                $tA['delivery']['delivery_name'] = $tInfo['name'];
                $tA['delivery']['delivery_mobile'] = $tInfo['mobile'];
                $tA['delivery']['delivery_portrait'] = $tInfo['portrait'];
                $tA['delivery']['delivery_status'] = $tInfo['status'];
            }
        }
        $product = $this->mOrder->getOrderProductList($orderId);

        if(!$product){
            show_404();
        }
        //缺货处理
        $tA['shortage_handing']['list'] = $this->mOrder->getShortage($tA['shortage_handing']['value']);

        $this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
        if ($tMsg = $this->mMsg->getOrderMsg($this->userId,$orderId)){
            foreach ($tMsg as $k=>$v){
                //阅读信息
                $data = array(
                    'consumer_id'=>$this->userId,
                    'message_id'=>$v['id'],
                    'is_delete'=>0,
                    'addtime'=>time(),
                );
                $this->mMsg->saveStatus($data);
            }
        }
        $tData = array(
            'title' =>'订单详情',
            'active' => 'order',
            'product' => $product,
            'info' => $tA
        );

        $this->view('order/orderDetail', $tData, 'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * 对订单商品进行评价
     */
    public function saveComment(){

      if($_POST){
      //表单验证
      $vConf = array(
          array('order_id', '订单id', 'required|is_natural_no_zero'),
//          array('product_id', '订单商品', 'required'),
//          array('service_tags', '服务评分标签', 'required'),
          array('service_score', '服务评分', 'required|is_natural_no_zero|in_list[1,2,3,4,5]'),
//            array('deliveryman_tags', '配送员评分标签', 'required'),
//            array('deliveryman_score', '配送员评分', 'is_natural_no_zero|in_list[1,2,3,4,5]'),
      );
      $this->formDataValidation($vConf);
      $orderId = post('order_id');
      $serviceTags = post('service_tags'); // 菜好,肉多 多个以逗号隔开
      $serviceScore = (int)post('service_score'); // 服务评分
      $deliverymanTags = post('deliveryman_tags'); // 长得帅,跑得快 多个以逗号隔开
      $deliverymanScore = post('deliveryman_score'); // 配送员评分
      $productIds = post('order_product_id');
      $productScore = post('product_score');
      $content = post('content');
      $serviceTags = trim($serviceTags, ',');
      $deliverymanTags = trim($deliverymanTags, ',');

      //加载模型
      $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
      $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
      $this->loadModel('DlnOrderModel', 'mDOrder', 'deliveryman');
      $this->loadModel('DlnCommentModel', 'mDComment', 'deliveryman');
      $this->loadModel('merchantCommentModel', 'mComment', 'merchant');

      //验证订单是否存在
      $tOrder = $this->mOrder->getInfo($orderId,$this->userId,0,true);
      if ( ! $tOrder){
          $this->appReturn(0,'订单不存在');
      }
      if($tOrder['status'] != 4){
          $this->appReturn(0,'该订单不能评论');
      }
      if($tOrder['is_comment'] == 2){
          $this->appReturn(0,'已经评论过');
      }
//      if($tOrder['shipping_type'] == 2 && !$deliverymanTags){
//          $this->appReturn(0,'配送员评分标签必须');
//      }
      if($tOrder['shipping_type'] == 2 && $tOrder['expense_type'] == 1 && !$deliverymanScore){
          $deliverymanScore = 5;
//          $this->appReturn(0,'配送员评分必须');
      }

      //验证该订单产品
      $tProduct = $this->mOrder->getOrderProductInfoByIds(array(), $orderId, 0, true);

      if (count($productIds) != count($tProduct)){
          $this->appReturn(0,count($productIds).'订单商品数据错误'.count($tProduct));
      }

      $time = time();
      $data = array();
      foreach ($productIds as $k => $v) {
          //上传图片
          $imgPath = array();
          $images = post('images'.$v);
          $path = 'uploads/product/comment/'.$orderId;
          if ( ! empty($images)){
              $imgPath = saveCSVimg($images, $path, uniqid());
              if (empty($imgPath)) {
                  $this->ajaxReturn(0, '图片上传失败');
              }
          }
          $data[] = array(
              'order_id' => $orderId,
              'product_id' => $tProduct[$v]['product_id'],
              'order_product_id' => $v,
              'consumer_id' => $this->userId,
              'merchant_id' => $tOrder['merchant_id'],
              'score' => (int)$productScore[$k],
              'service_score' => $serviceScore,
              'tags' => ','.$serviceTags,
              'content' => $content[$k],
              'reply' => '',
              'imgs' => json_encode($imgPath),
              'admin_reply' => '',
              'addtime' => $time,
          );

      }

      //事务
      $this->db->trans_begin();
      $tRS = $this->mComment->save($data, 0, true);
      if (! $tRS){
          $this->db->trans_rollback();
          $this->appReturn(0,'保存失败');
      }

      // 更改订单状态/评论状态
      $oSave = $this->mOrder->save(array('status' => 5, 'is_comment' => 2), 0, $orderId);
      if ( ! $oSave){
          $this->db->trans_rollback();
          $this->appReturn(0,'保存失败');
      }

      //统计商家平均分
      $tAvgScore = $this->mComment->totalCommentScore($tOrder['merchant_id']);
      if ( ! $this->mMerchant->save(array('score'=>$tAvgScore),$tOrder['merchant_id'])){
          //平均分没有保存成功
      }
          //存在推荐人
      $parentInfo = [];
      if($tOrder['parent_id'] > 0){
              $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
              $sharePercent = $this->mSetting->get('share_percent');
              if($sharePercent > 0){
                  $balanceLog = [
                      'consumer_id' => $tOrder['parent_id'],
                      'type' => 7,
                      'pay_type' => 7,
                      'param' => $orderId,
                      'amount' => sprintf('%.2f', ($tOrder['reality_amount']*$sharePercent)/100),
                      'status' => 2,
                      'addtime' => time(),
                      'confirm_time' => time(),
                  ];
                  $parentInfo = $this->mUser->getInfo($tOrder['parent_id']);
                  if ( ! $this->mUser->saveBuyLog($balanceLog)){
                      $this->db->trans_rollback();
                      $this->appReturn(0,'保存失败');
                  }
                  $cData[] = [
                      'id' => $tOrder['parent_id'],
                      'balance' => $parentInfo['balance'] + $balanceLog['amount'],
                  ];

                  $query = $this->mUser->updateBatch($this->mUser->tbUser, $cData, 'id');
                  if ( ! $query){
                      $this->db->trans_rollback();
                      $this->appReturn(0,'分享数据保存失败');
                  }
              }
          //首单 分享注册送红包
          $this->db->select('id,code')
              ->where('status', 5)
              ->where('consumer_id', $this->userId);
          $count = $this->mOrder->count($this->mOrder->tbOrder);

          if($count == 1 && $parentInfo){
              $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

              $this->db->select('id,name,type,money,surplus_number')
                  ->where(array('type' => 1,'status'=> 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
              $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);
              if($bonusList){
                  $bA = array();
                  $else = array();
                  foreach ($bonusList as $v){
                      $bA[] = array(
                          'bonus_id' => $v['id'],
                          'type' => $v['type'],
                          'consumer_id' => $tOrder['parent_id'],
                          'money' => $v['money'],
                          'status' => 1,
                          'param' => $orderId,
                          'addtime' => time()
                      );
                      $else[] = array(
                          'id' => $v['id'],
                          'surplus_number' => $v['surplus_number'] - 1,
                      );
                  }
                  if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                      $this->db->trans_rollback();
                      $this->ajaxReturn(0, '红包赠送失败');
                  }
                  //更新剩余红包数量
                  if(!($this->mPromotion->save($else, 0, true))){
                      $this->db->trans_rollback();
                      $this->ajaxReturn(0, '红包赠送失败');
                  }
              }
          }

      }
      //平台配送
      if($tOrder['shipping_type'] == 2 && $tOrder['expense_type'] == 1){
          // 获取配送员信息
          $dInfo = $this->mDOrder->getDeliverymanInfoByOrderIds(array($orderId));

          if (empty($dInfo)){
              $this->appReturn(0, '获取配送员信息失败');
          }

          // 配送员评价信息
          $dlnData = array(
              'order_id' => $orderId,
              'deliveryman_id' => $dInfo[$orderId]['deliveryman_id'],
              'tags' => ','.$deliverymanTags,
              'score' => $deliverymanScore,
              'addtime' => $time
          );
          $dId = $this->mDComment->save($dlnData);
          if (!$dId){
              $this->db->trans_rollback();
              $this->appReturn(0,'保存失败');
          }
          //统计配送员平均分
          $tAvgScore = $this->mDComment->totalCommentScore($dInfo[$orderId]['deliveryman_id']);
          $this->mDComment->update($this->mDComment->tbUser, array('score' => $tAvgScore));

      }

      $this->db->trans_commit();
      $this->ajaxReturn(1,'评论成功', null,getUrl('order/orderList?type='.$tOrder['expense_type'].'&page=1'));
  }
      $orderId = (int)get('order_id');
      $tA = $this->mOrder->getInfo($orderId,$this->userId,0,true);
      if ( ! $tA){
        show_404();
      }
        //商品信息
        $product = $this->mOrder->getOrderProductList($orderId);
        if(!$product){
            show_404();
        }
        $tInfo = array();
        if ($tA['shipping_type'] == 2){//平台配送
            $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');
            $deliveryman = $this->mDln->getDeliverymanInfoByOrderIds(array($orderId));
            $tInfo = isset($deliveryman[$orderId])?$deliveryman[$orderId]:array();

        }
      $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
      //店铺标签
      $merchant_tags = $this->mSetting->get('merchant_comment_tags');
       //配送员标签
        $dlyTag = array();
        if($tA['expense_type'] == 1 && $tA['shipping_type'] == 2){
            $dlyTag = $this->mSetting->get('deliveryman_comment_tags', 'deliveryman');
            $dlyTag = json_decode($dlyTag);
        }

        $tData = ['title' => '评论',
                    'delivery' => $tInfo,
                    'product' => $product,
                    'dlyTag' => $dlyTag,
                    'merchant_tags' => json_decode($merchant_tags)
                ];
      $this->view('order/comment',$tData,'wx_validation,toastmessage,layer_mobile');
    }


    /**
     * 申请售后服务
     */
    public function saveService(){

        if($_POST){
            //表单验证
            $vConf = array(
                array('order_id', '订单id', 'required|is_natural_no_zero'),
                array('reason', '售后原因', 'required'),
                array('amount', '售后金额', 'required'),
            );
            $this->formDataValidation($vConf);
            $orderId = post('order_id');
            $remark = trim(post('remark'));
            $reason = trim(post('reason'));//售后原因
            $amount = trim(post('amount'));//售后金额
            $images         = post('images'); // 图片
            //加载模型
            $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

            $tService = $this->mOrder->getServiceInfo(0,$orderId);
            if ( ! empty($tService) && in_array($tService['status'], array(2,3))){
                $this->appReturn(0,'请勿重复提交售后');
            }
            //验证订单是否存在
            $tOrder = $this->mOrder->getInfo($orderId,$this->userId);
            if ( ! $tOrder){
                $this->appReturn(0,'订单不存在');
            }
            if ($tOrder['status'] != 2 && $tOrder['status'] != 3 && $tOrder['status'] != 4){
                $this->ajaxReturn(0, '不能申请售后');
            }
            //限制售后次数
            $serviceCount = $this->mOrder->hasOrderServiceCount($orderId, $this->userId);
            if($serviceCount >= 2){
                $this->ajaxReturn(0, '已达申请售后次数上限，请联系平台');
            }
            if ($amount > $tOrder['reality_amount']){
                $this->ajaxReturn(0, '退款金额不能大于'.$tOrder['reality_amount'].'元');
            }
            // 修改商品售后状态
            $this->db->trans_begin();
            $op = $this->mOrder->save(array('after_sale' => 2), 0, $orderId);
            if (!$op){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
            //上传图片
            $imgs = array();
            $path = 'uploads/product/service/'.$orderId;
            if ( ! empty($images)){
                $imgs = saveCSVimg($images, $path, uniqid());
                if (empty($imgs)) {
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '图片上传失败');
                }
            }
            /**
             * 数据
             * @var array $data
             */
            $service_code = getOrderCode();
            $data = array(
                'merchant_id'=>$tOrder['merchant_id'],
                'consumer_id'=>$this->userId,
                'code'=>$service_code,
                'order_id'=>$orderId,
                'refund_amount'=>$amount,
                'remark'=>$remark,
                'reason'=>$reason,
                'pic'=>json_encode($imgs),
                'order_status' => $tOrder['status'],
                'status'=>3,
                'addtime'=>time(),
            );

            if ( !$tSId = $this->mOrder->saveService($data)){
                $this->db->trans_rollback();
                $this->appReturn(0,'申请失败');
            }


            $this->loadModel('MerchantMessageModel', 'mMerMsg','merchant');
            $this->loadModel('MerchantUserModel', 'mMerchant','merchant');

            $tMerchant = $this->mMerchant->getMiniInfo($tOrder['merchant_id']);

            //给商家的推送消息
            $title = '您有一条售后订单';//商家消息标题
            $merMsg = array(
                'merchant_id'=>$tOrder['merchant_id'],
                'type'=>4,
                'order_id'=>$tSId,
                'title'=>$title,
                'content'=>'消费者于'.date('Y/m/d H:i:s').'对订单商品申请售后服务！请及时前往处理',
                'addtime'=>time(),
            );

            //保存商家消息
            if ( ! $msgId = $this->mMerMsg->save($merMsg)){
                $this->db->trans_rollback();
                $this->appReturn(0,'保存失败');
            }
            // 添加操作记录
            $rS = $this->mOrder->saveOrderLog($orderId, $tOrder['status_str'], "消费者申请售后",$this->port, $this->userId);
            if (!$rS){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
            $this->db->trans_commit();
            //通知商家
            MerchantJpush($title,$title,4, $tMerchant['jpush_code'],4, $tSId);

            $this->ajaxReturn(1,'申请成功',null, getUrl('order/getServiceList'));

        }

        $orderId = (int)get('order_id');

        $tA = $this->mOrder->getInfo($orderId,$this->userId);
        if ( ! $tA){
            show_404();
        }

        if ($tA['shipping_type'] == 2){//平台配送
            $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');
            $deliveryman = $this->mDln->getDeliverymanInfoByOrderIds(array($orderId));
            $tInfo = isset($deliveryman[$orderId])?$deliveryman[$orderId]:array();
            if($tInfo){
                $tA['delivery']['delivery_name'] = $tInfo['name'];
                $tA['delivery']['delivery_mobile'] = $tInfo['mobile'];
                $tA['delivery']['delivery_portrait'] = $tInfo['portrait'];
                $tA['delivery']['delivery_status'] = $tInfo['status'];
            }
        }
        //商品信息
        $product = $this->mOrder->getOrderProductList($orderId);
        if(!$product){
            show_404();
        }
        //售后原因
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $reason = $this->mSetting->get('aftersale_reason', 'admin');
        $reasonData = array();
        if($reason){
            $reason = json_decode($reason,true);
            foreach ($reason as $k=>$v){
                $reasonData[] = array('label' => $v,'value' => $k);
            }
        }

        $tData = array(
            'title' => '申请售后',
            'info' => $tA,
            'product' => $product,
            'reason' => json_encode($reasonData, JSON_UNESCAPED_UNICODE)
        );

        $this->view('order/saveService', $tData, 'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * 获取售后服务列表
     */
    public function getServiceList(){

        $page = get('page');
        $status = get('status');

        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->appGetServiceList($this->userId, 0, $page, $status);

//        if ( ! $tA){
//            show_404();
//        }

        $this->view('order/serviceList', ['title' => '售后订单','list' => $tA, 'status' => $status]);

    }

    /**
     * ajax获取售后列表
     */
    public function ajaxGetServiceList(){

        $page = post('page');
        $status = post('status');
        $page += 1;
        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->appGetServiceList($this->userId, 0, $page, $status);
        $this->ajaxReturn(1, '', $tA);
    }

    /**
     * 获取售后服务详情
     */
    public function getServiceDetail(){

        $serviceId = get('service_id');//售后id

        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getServiceInfo(0,  0, 0, $this->userId, 0, $serviceId);
        if ( ! $tA){
            $this->appReturn(0,'数据为空');
        }

        $product = $this->mOrder->getProductList(0,  $serviceId, $this->userId);
        if ( ! $product){
            $this->appReturn(0,'数据为空');
        }
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $tShop = $this->mMerchant->getShopInfo($tA['merchant_id']);

        $tA['base'] = array(
            'code'=>$tA['code'],
            'order_code'=>$tA['order_code'],
            'addtime'=>$tA['addtime'],
        );

        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $service_tel = $this->mSetting->get('web_service_tel');

        $tA['shop'] = array(
            'shop_name'=>isset($tShop['shop_name'])?$tShop['shop_name']:'商家名称',
            'portrait'=>isset($tShop['portrait'])?$tShop['portrait']:getDefaultImg(),
            'address'=>$tShop['address_desc'],
            'store_tel'=>isset($tShop['store_tel'])?$tShop['store_tel']:'暂无电话',
            'service_tel'=>$service_tel,
            'longitude'=>isset($tShop['longitude'])?$tShop['longitude']:'0',
            'latitude'=>isset($tShop['latitude'])?$tShop['latitude']:'0',
            'easemob_merchant_code' => $tShop['jpush_code'],
        );

        foreach ($product as $k => $v){
            $tA['product'][$k] = $v;
        }

        $tA['service'] = array(
            'reason'=>$tA['reason'],
            'remark'=>$tA['remark'],
            'complete_remark'=>$tA['complete_remark'],
            'complete_time'=>$tA['complete_time'],
        );

        $this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
        //改变消息状态
        $message = $this->mMsg->getInfo(0, $this->userId, $tA['id']);
        if ($message){
            // 添加消息查看记录
            if ($message['viewed'] == 1) {
                $messageData = array(
                    'consumer_id' => $this->userId,
                    'message_id' => $message['id'],
                    'is_delete' => 0,
                    'addtime' => time(),
                );

                if ( ! $this->mMsg->saveStatus($messageData)){
                    $this->ajaxReturn(0, '添加消息查看记录失败');
                }

            }
        }
        unset($product,$tA['reason'],$tA['remark'],$tA['complete_remark'],$tA['complete_time'],$tA['status_format_str'],
            $tA['consumer_id'],$tA['pay_type'],$tA['platform_remark'],$tA['order_status'],$tA['jpush_code']);
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $web_service_tel = $this->mSetting->get('web_service_tel');

        $this->view('order/serviceDetail', ['title' => '售后详情', 'info'=> $tA,'web_service_tel' => $web_service_tel]);

    }

}
	